package com.cn.intelligence.bean;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class Md5 {
    private static final char hexDigits[]   = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public String md5MultipartFile(MultipartFile file) throws NoSuchAlgorithmException, IOException {
        if (null == file) {
            return "";
        }

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();

        byte[] buff = new byte[2048];
        int len;
        InputStream fis = file.getInputStream();
        while ((len = fis.read(buff)) != -1) {
            md.update(buff, 0, len);
        }

        fis.close();

        return bufferToHex(md.digest());
    }

    public String md5File(File file) throws NoSuchAlgorithmException, IOException {
        if (null == file) {
            return "";
        }

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        FileInputStream fis = new FileInputStream(file);
        byte[] buff = new byte[2048];
        int len;
        while ((len = fis.read(buff)) != -1) {
            md.update(buff, 0, len);
        }

        fis.close();

        return bufferToHex(md.digest());
    }

    public String md5String(String sourceString) throws NoSuchAlgorithmException, IOException {
        if (null == sourceString) {
            return "";
        }

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();

        byte[] buff = sourceString.getBytes("UTF-8");
        md.update(buff);

        return bufferToHex(md.digest());
    }

    private String bufferToHex(byte bytes[])
    {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private String bufferToHex(byte bytes[], int m, int n)
    {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++)
        {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private void appendHexPair(byte bt, StringBuffer stringbuffer)
    {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}